from flask import jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.api.v1 import bp
from app.models.operation_log import OperationLog
from app.models.user import User
from app import db

@bp.route('/logs', methods=['GET'])
@jwt_required()
def get_logs():
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    if user.role != 'admin':
        return jsonify({'error': '权限不足'}), 403
        
    logs = OperationLog.query.order_by(OperationLog.created_at.desc()).all()
    return jsonify([{
        'id': log.id,
        'user': log.user.username,
        'operation_type': log.operation_type,
        'operation_detail': log.operation_detail,
        'ip_address': log.ip_address,
        'created_at': log.created_at.strftime('%Y-%m-%d %H:%M:%S')
    } for log in logs])

@bp.route('/logs', methods=['POST'])
@jwt_required()
def create_log():
    user_id = get_jwt_identity()
    data = request.get_json()
    
    log = OperationLog(
        user_id=user_id,
        operation_type=data['operation_type'],
        operation_detail=data.get('operation_detail'),
        ip_address=request.remote_addr
    )
    db.session.add(log)
    db.session.commit()
    
    return jsonify({'message': '日志记录成功'}), 201 